package com.leo;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Scene;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;

/**
 * @ClassName ListViewFilter
 * @Description 过滤
 * @Author wangss
 * @date 2020.06.11 23:56
 * @Version 1.0
 */
public class ListViewFilter extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        AnchorPane anchorPane = new AnchorPane();
        anchorPane.setStyle("-fx-background-color: #fff2f2");

        TextField tf = new TextField();
        tf.setPromptText("请输入");

        ListView<String> listView = new ListView();
        listView.setPrefWidth(400d);
        listView.setPrefHeight(400d);

        ObservableList<String> obsList = listView.getItems();
        obsList.add("wangss -- 123");
        obsList.add("ztt -- 4561");
        obsList.add("bbb -- 4562");
        obsList.add("we -- 1234");
        obsList.add("adf -- 4565");
        obsList.add("adf -- 456f");
        obsList.add("fesef -- 456d");

        anchorPane.getChildren().addAll(tf, listView);
        AnchorPane.setTopAnchor(tf, 100d);
        AnchorPane.setLeftAnchor(tf, 100d);
        AnchorPane.setTopAnchor(listView, 140d);
        AnchorPane.setLeftAnchor(listView, 100d);

        Scene scene = new Scene(anchorPane);
        primaryStage.setScene(scene);
        primaryStage.setWidth(800d);
        primaryStage.setHeight(800d);
        primaryStage.setTitle("搜索功能");
        primaryStage.setResizable(false);
        primaryStage.show();

        tf.textProperty().addListener((observable, oldValue, newValue) -> {
            FilteredList<String> filtered = obsList.filtered(str -> {
                if (str.contains(newValue)) {
                    return true;
                } else {
                    return false;
                }
            });
            listView.setItems(filtered);
        });
    }
}
